package com.jlkf.controller;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.platform.server.util.StringTools;
public class BaseController {
	protected final Logger log = LoggerFactory.getLogger(getClass());//子类可直接用此log对象打印日志
	protected HttpServletRequest request;
	protected HttpServletResponse response;

	
	@ModelAttribute
	public void setReqAndResp(HttpServletRequest request,HttpServletResponse response) {
		response.addHeader("Access-Control-Allow-Origin", "*");
		this.request = request;
		this.response = response;
	}
	
	public String getInputStr(HttpServletRequest request , String charset){
    	try{
    		String encoding = null;
    		if(StringTools.isEmpty(charset)){
    			encoding = "UTF8";
    		}
    		else{
    			encoding = charset;
    		}
    		//获取输入流
            InputStream is = request.getInputStream();
            //获取输入字符串
            return IOUtils.toString(is, encoding);
    	}
    	catch(Exception e){
    		log.error(e.getMessage(),e);
    	}
    	return "";
    }	
	
	public static String getClientIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (StringTools.isEmpty(ip) || "unknown".equalsIgnoreCase(ip.trim())) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringTools.isEmpty(ip) || "unknown".equalsIgnoreCase(ip.trim())) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringTools.isEmpty(ip) || "unknown".equalsIgnoreCase(ip.trim())) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	public static String getLocaleMessage(HttpServletRequest request,Object[] args,String code){
        WebApplicationContext ac = RequestContextUtils.getWebApplicationContext(request);
        return ac.getMessage(code,args, RequestContextUtils.getLocale(request));
    }
	
	/**通过servlet输出controller返回结果*/
	protected void writeResult(String result) {
	    try {
	    	response.addHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/json; charset=utf-8");
			response.setHeader("Cache-Control", "no-cache");
			response.setCharacterEncoding("utf-8");  
			response.getWriter().print(result);
		} catch (IOException e) {
			log.error("error msg:",e);
		}
	}
	
}
